package org.cloudlab.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.cloudlab.bean.Paper;
import org.cloudlab.common.ResponseResult;
import org.cloudlab.service.IPaperService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 文章的控制器
 *
 * @author Liu Yicong
 * @date 2023/9/7
 */
@CrossOrigin // 允许跨域访问
@RestController
@RequestMapping(value = "paper")
public class PaperController {

	private static final Logger logger = LoggerFactory.getLogger(PaperController.class);

	@Autowired
	private IPaperService paperService;

	/**
	 * 查询页面
	 */
	@RequestMapping("queryByPage")
	public ResponseResult<Page<Paper>> queryByPage(Page<Paper> page, Paper paper, String onlyOwn) {
		Page<Paper> list = paperService.queryByPage(page, paper, onlyOwn);
		return ResponseResult.success("查询成功", list);
	}

	/**
	 * 查询用户的所有文章(下拉框)
	 */
	@GetMapping("queryByUserId")
	public ResponseResult<List<Paper>> queryByUserId() {
		List<Paper> list;
		try {
			list = paperService.queryByUserId();
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail("查询失败", null);
		}
		return ResponseResult.success("查询成功", list);
	}


	/**
	 * 添加文章
	 *
	 * @param paper 文章属性
	 */
	@PostMapping("add")
	public ResponseResult<String> add(@RequestBody Paper paper) {
		try {
			paperService.add(paper);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail("添加失败, 看看是否已经有名称缩写相同的文章吧", null);
		}
		return ResponseResult.success();
	}

	/**
	 * 更新
	 *
	 * @param paper 文章属性, 其中id为必须的
	 */
	@PostMapping("update")
	public ResponseResult<String> update(@RequestBody Paper paper) {
		try {
			paperService.update(paper);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail(e.getMessage(), null);
		}
		return ResponseResult.success();
	}

	/**
	 * 删除
	 *
	 * @param paperId 期刊id
	 */
	@GetMapping("remove")
	public ResponseResult<String> remove(Long paperId) {
		try {
			paperService.delete(paperId);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail(e.getMessage(), null);
		}
		return ResponseResult.success();
	}

}
